package com.lsa.skienna.challenge.chap12;

public class Travesal {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		snake_order(8, 9);
		diagonal_order(5, 5);
	}

	private static void snake_order(int n, int m) {
		int[][] array = new int[n][m];
		int k = 0;
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++)
				process(array, i, j + (m - 2 * j - 1) * ((i + 1) % 2), ++k);

		printArray(array);
	}

	private static void diagonal_order(int n, int m) {
		int[][] array = new int[n][m];
		int k = 0;
		int d, j; /* diagonal and point counters */
		int pcount; /* points on diagonal */
		int height; /* row of lowest point */
		for (d = 1 ; d <= m + n - 1; d++) {
			height = 1 + Math.max(0, d - m);
			pcount = Math.min(d, (n - height + 1));
			for (j = 0; j < pcount; j++)
				process(array, Math.min(m, d) - j - 1, height + j - 1, ++k);
		}
		printArray(array);
	}

	private static void process(int[][] array, int i, int j, int k) {
		array[i][j] = k;
	}

	private static void printArray(int[][] array) {
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array[i].length; j++) {
				System.out.print(String.format("%2s ", array[i][j]));
			}
			System.out.println();
		}
	}
}
